package org.lovely.websocket;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.lovely.base.domain.entity.WebSocketMsgDTO;
import org.springframework.stereotype.Component;

import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.ConcurrentHashMap;

/**
 * <p>
 * description:  websocket  服务器
 * </p>
 *
 * @author kaitong.wang@hand-china.com 2021/3/31 16:31 星期三
 */
@Slf4j
@Component
@ServerEndpoint("/websocket/{userId}")
public class DeerWebSocketServer {

    /**
     * 存储已经存在的 websocket 服务器
     */
    public static ConcurrentHashMap<Long,DeerWebSocketServer> webSocketMap = new ConcurrentHashMap<>();

    private  Session session;


    @OnOpen
    public void onOpen(Session session, @PathParam("userId") Long userId) {
        this.session = session;
        System.out.println("-------------------建立链接："+userId);
        if(webSocketMap.containsKey(userId)){
            webSocketMap.remove(userId);
            webSocketMap.put(userId,this);
            //加入set中
        }else{
            webSocketMap.put(userId,this);
        }

            JSONObject jsonObject= new JSONObject();
            jsonObject.put("title","");
            jsonObject.put("message","尊敬的用户您已登录成功！");
//        WebSocketMsgDTO webSocketMsgDTO = WebSocketMsgDTO.builder().title("").message("尊敬的用户您已登录成功").build();

//        sendMessage(webSocketMsgDTO,userId);
    }
    /**
     * 实现服务器主动推送
     */
    public void sendMessage(String message) throws IOException {
        System.out.println("要发送的消息为："+message);
        this.session.getBasicRemote().sendText(message);
    }

    public   void sendMessage(WebSocketMsgDTO  message, Long userId) {
        System.out.println("要发送的消息为："+JSON.toJSONString(message));
        if(webSocketMap.containsKey(userId)){
            System.out.println("存在用户");
            DeerWebSocketServer deerWebSocketServer = webSocketMap.get(userId);
            try {
                deerWebSocketServer.sendMessage(JSON.toJSONString(message));
            } catch (IOException e) {
                e.printStackTrace();
//                log.error("发送消息失败",e.getMessage());
            }

        }
    }
}
